<template>
  <div id="single-choice"
       class="task-single-choice">
    <!-- 每个程序设计题 -->
    <div class="task-single-main"
         :id="'program'+opIndex"
         v-for="(option,opIndex) in FormData.programmingData"
         :key="opIndex">
      <Card dis-hover>
        <div class="clearfix">
          <span v-if="option.programmingQuestionId"> {{opIndex+1}}.{{option.programmingQuestionInfo.title}}</span>
        </div>
        <div v-html="option.programmingQuestionInfo.description" class="problemDescription"></div>
        <div>
          <Card dis-hover v-if="option.programmingQuestionId != -1" :padding="20" id="submit-code" style="border:transparent;">
            <div class="codeEditor">
              <Select class="languageSelect" v-model="option.language" placeholder="请选择编程语言">
                <Option
                  v-for="item in option.programmingQuestionInfo.languages"
                  :key="item"
                  :label="item"
                  :value="item">
                </Option>
              </Select>
              <codemirror
                style="border: 1px solid darkgrey"
                v-model="option.code"
                :options="options">
              </codemirror>
              <div style="height:30px;position:relative;margin-top:20px;">
                <div style="display:inline;width:50%;float:left;">
                  <!-- 有提交记录 -->
                  <div class="status" v-if="option.statusVisible" style="">
                    <template>
                      <span>{{$t('m.Status')}}</span>
                      <Tag type="dot" :color="submissionStatus(option).color" @click.native="handleRoute('/status/'+submissionId)">
                        {{$t('m.' + submissionStatus(option).text.replace(/ /g, "_"))}}
                      </Tag>
                    </template>
                  </div>
                </div>
                <div style="display:inline;width:50%;float:right;">
                  <Button type="warning" icon="edit" :loading="option.submitting" @click="submitCode(option)"
                      :disabled="option.submitted" style="float:right;">
                    <span v-if="option.submitting">{{$t('m.Submitting')}}</span>
                    <span v-else>{{$t('m.Submit')}}</span>
                  </Button>
                </div>
              </div>
            </div>
          </Card>
        </div>
      </Card>
      <div class="hr" v-if="opIndex!=FormData.programmingData.length-1"/></div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import {codemirror} from 'vue-codemirror-lite'
import api from '@oj/api'
import 'codemirror/theme/ambiance-mobile.css'
import {JUDGE_STATUS} from '@/utils/constants'
export default {
  name: 'Program-choice',
  props: ['FormData'],
  components: {
    codemirror
  },
  data () {
    return {
      visible: false,
      visible2: [],
      questions: [],
      options: {
        tabSize: 2,
        theme: 'ambiance-mobile',
        lineNumbers: true,
        line: true,
        mode: 'text/x-c++',
        foldGutter: true,
        matchBrackets: true
      },
      theme: 'solarized',
      type: 'Homework',
      language: ''
    }
  },
  created () {
    setTimeout(() => { this.init() }, 200)
  },
  methods: {
    init () {
      this.FormData.programmingData.forEach(_ => {
        this.visible2.push(false)
        this.FormData.studentScore += Math.round(_.studentScore) // 之前有提交记录，设置学生已得分数
      })
    },
    checkSubmissionStatus (option) {
      // 使用setTimeout避免一些问题
      if (this.refreshStatus) {
        // 如果之前的提交状态检查还没有停止,则停止,否则将会失去timeout的引用造成无限请求
        clearTimeout(this.refreshStatus)
      }
      const checkStatus = () => {
        let id = option.submissionId
        api.getHomeworkSubmission(id).then(res => {
          option.result = res.data.data
          // 没有提交记录
          if (!option.result) {
            this.FormData.studentScore = 0
          }
          // 有提交记录
          if (Object.keys(res.data.data.statistic_info).length !== 0) {
            // 判题成功，返回结果
            option.submitting = false
            option.submitted = true
            clearTimeout(this.refreshStatus)
            // 学生分数：OI计算成绩模式下才有score分数，题目满分需要再创建题目时进行设置，默认100分制
            this.FormData.studentScore += Math.round(option.result.statistic_info.score / 100 * option.score)  // 设置提交返回结果的学生分数，以100分制按比例计算所得分数
            this.updateHomeworkScore()
          } else {
            // 判题中
            this.refreshStatus = setTimeout(checkStatus, 2000)
          }
        }, res => {
          option.submitting = false
          clearTimeout(this.refreshStatus)
        }).catch(e => {
        })
      }
      this.refreshStatus = setTimeout(checkStatus, 2000)
    },
    updateHomeworkScore () {
      let passData = {
        classroom_id: this.$route.params.classroomId,
        homework_id: this.FormData.homework_id,
        score: this.FormData.studentScore
      }
      // 提交作业分数
      api.postClassroomStudentHomeworkStatus(passData).then(res => {})
    },
    submitCode (option) {
      // 检验学生提交信息
      if (!option.language) {
        this.$Message.error('请选择编程语言')
        return
      }
      if (option.code.trim() === '') {
        this.$error(this.$i18n.t('m.Code_can_not_be_empty'))
        return
      }
      // 验证成功后进行代码提交
      option.submissionId = ''
      option.result = {result: 9}
      option.submitting = true
      let passData = {
        problem_id: option.programmingQuestionInfo.id,
        language: option.language,
        code: option.code,
        classroom_id: this.$route.params.classroomId,
        homework_id: this.FormData.homework_id
      }
      const submitFunc = (passData, detailsVisible) => {
        option.statusVisible = true
        api.submitHomeworkCode(passData).then(res => {
          option.submissionId = res.data.data && res.data.data.submission_id
          // 定时检查状态
          option.submitting = false
          option.submissionExists = true
          if (!detailsVisible) {
            this.$Modal.success({
              title: this.$i18n.t('m.Success'),
              content: this.$i18n.t('m.Submit_code_successfully')
            })
            return
          }
          option.submitted = true
          this.checkSubmissionStatus(option)
        }, res => {
          option.submitting = false
          option.statusVisible = false
        }).catch(e => {
        })
      }
      submitFunc(passData, true)
    }
  },
  computed: {
    ...mapGetters(['problemSubmitDisabled', 'contestRuleType', 'OIContestRealTimePermission', 'contestStatus']),
    submissionStatus () {
      return function (option) {
        return {
          text: JUDGE_STATUS[option.result.result]['name'],
          color: JUDGE_STATUS[option.result.result]['color']
        }
      }
    },
    submissionRoute () {
      if (this.contestID) {
        return {name: 'contest-submission-list', query: {problemID: this.problemID}}
      } else {
        return {name: 'submission-list', query: {problemID: this.problemID}}
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin-top: 20px;
  margin-bottom: 20px;
  width: 100%;
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #E4E7ED;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
  line-height: 36px;
  text-align:center;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.problemDescription {
  font-size: 12px;
  margin: 20px 0 0 20px;
}
.submitBtn {
  margin-left: 45%;
  margin-top: 20px;
}
.languageSelect {
  margin: 20px 0;
  width: 200px;
}
.codeEditor {
  margin-top: -24px;
}
.programmingAction {
  width: 100%;
  margin-top: 20px;
}
</style>
